package zaijiansunwukong.util;

import com.itextpdf.text.pdf.*;

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;


/**
 * Created by Administrator on 2016/4/20.
 */
public class PdfUtils implements Serializable {

    static Logger logger = Logger.getLogger(PdfUtils.class);

    /**
     * html转pdf。html  最大尺寸790,1120
     * @param html
     * @param outputFile
     * @throws Exception
     */
    public static void htmlToPdf(String html,String outputFile) throws Exception{
        OutputStream os = null;
        try {
            os = new FileOutputStream(outputFile);
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocumentFromString(html);
            // 解决中文问题
            //Arial Unicode MS   SimSun Microsoft YaHei
            String freemarkerFontPath = "/home/weblogic/data/web/sfs/freemarker";
            if (StringUtils.isBlank(freemarkerFontPath)) {
                logger.error("freemarkerFontPath is blank!");
                return;
            }
            String msyhPath = freemarkerFontPath + "/MSYH.TTF";
            File msyhFile = new File(msyhPath);
            if (!msyhFile.exists() || !FileUtil.isReadable(msyhFile)) {
                logger.error("MSYH.TTF does not exist or permission denied !");
            }
            String msyhbdPath = freemarkerFontPath + "/MSYHBD.TTF";
            File msyhbdFile = new File(msyhbdPath);
            if (!msyhbdFile.exists() || !FileUtil.isReadable(msyhbdFile)) {
                logger.error("MSYHBD.TTF does not exist or permission denied !");
            }
            ITextFontResolver fontResolver = renderer.getFontResolver();
            fontResolver.addFont(msyhPath, BaseFont.IDENTITY_H,
                    BaseFont.NOT_EMBEDDED);
            fontResolver.addFont(msyhbdPath, BaseFont.IDENTITY_H,
                    BaseFont.NOT_EMBEDDED);
            //renderer.getSharedContext().setBaseURL("http://192.168.0.138:8081/saferycom/images/");
            renderer.layout();
            renderer.createPDF(os);
            logger.info("转换成功！");
        } catch(Exception e) {
            logger.error("", e);
        } finally {
            if (os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    logger.error("", e);
                }
            }
        }
    }
    /**
     * html转pdf。html  最大尺寸790,1120
     * @param html
     * @throws Exception
     */
    public static byte[] htmlToPdf(String html) throws Exception{
        ByteArrayOutputStream os = null;
        try {
            os = new ByteArrayOutputStream();

            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocumentFromString(html);
            // 解决中文问题,
            //Arial Unicode MS  SimSun Microsoft YaHei SimHei
            String freemarkerFontPath = "E:\\javaWorkspace\\freemarker-html2pdf\\freemarker-html2pdf\\src\\main\\resources\\fonts";
            if (StringUtils.isBlank(freemarkerFontPath)) {
                logger.error("freemarkerFontPath is blank!");
                return null;
            }
            //宋体
            String simsunPath = freemarkerFontPath + "/simsun.ttc";
            File simsunFile = new File(simsunPath);
            if (!simsunFile.exists() || !FileUtil.isReadable(simsunFile)) {
                logger.error("simsun.ttc does not exist or permission denied !");
                return null;
            }
            //黑体
            String simheiPath = freemarkerFontPath + "/simhei.ttf";
            File simheiFile = new File(simheiPath);
            if (!simheiFile.exists() || !FileUtil.isReadable(simheiFile)) {
                logger.error("simhei.ttf does not exist or permission denied !");
                return null;
            }
            //微软雅黑
            // String msyhPath = freemarkerFontPath + "/MSYH.TTF";
            // File msyhFile = new File(msyhPath);
            // if (!msyhFile.exists() || !FileUtil.isReadable(msyhFile)) {
            //     logger.error("MSYH.TTF does not exist or permission denied !");
            //     return null;
            // }
            // String msyhbdPath = freemarkerFontPath + "/MSYHBD.TTF";
            // File msyhbdFile = new File(msyhbdPath);
            // if (!msyhbdFile.exists() || !FileUtil.isReadable(msyhbdFile)) {
            //     logger.error("MSYHBD.TTF does not exist or permission denied !");
            //     return null;
            // }

            //嵌入中文字体
            ITextFontResolver fontResolver = renderer.getFontResolver();
            fontResolver.addFont(simsunPath, BaseFont.IDENTITY_H,
                    BaseFont.NOT_EMBEDDED);
            fontResolver.addFont(simheiPath, BaseFont.IDENTITY_H,
                    BaseFont.NOT_EMBEDDED);
            // fontResolver.addFont(msyhPath, BaseFont.IDENTITY_H,
            //         BaseFont.NOT_EMBEDDED);
            // fontResolver.addFont(msyhbdPath, BaseFont.IDENTITY_H,
            //         BaseFont.NOT_EMBEDDED);
            //renderer.getSharedContext().setBaseURL("http://192.168.0.138:8081/saferycom/images/");
            renderer.layout();
            renderer.createPDF(os);
            logger.info("转换成功！");

            return os.toByteArray();
        } catch(Exception e) {
            logger.error("", e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    logger.error("", e);
                }
            }
        }

        return null;
    }

    /**
     * 图片转成pdf，其实就是new一个空白pdf，把图片等比例插入进去
     * @param imageBytes
     * @param fitWidth 等比例宽
     * @param fitHeight 等比例高
     * @return
     */
    public static byte[] imageToPdf(byte[] imageBytes, float fitWidth, float fitHeight) {
        Document document = null;
        PdfWriter writer = null;
        ByteArrayOutputStream baos = null;
        try {
            // 创建一个 Document 对象
            document = new Document();
            // 创建一个 ByteArrayOutputStream 来存储生成的 PDF
            baos = new ByteArrayOutputStream();

            // 创建 PdfWriter 实例
            writer = PdfWriter.getInstance(document, baos);

            // 打开文档
            document.open();

            // // 设置字体
            // com.itextpdf.text.Font font = new com.itextpdf.text.Font(BaseFont.createFont(), 12);
            // // 添加一个段落
            // Paragraph paragraph = new Paragraph("hello", font);
            // document.add(paragraph);
            // 将图片数据转换为 Image 对象
            Image image = Image.getInstance(imageBytes);
            // 设置图片大小（可选）
            image.scaleToFit(fitWidth, fitHeight);  // 设置图片的最大宽度和高度（单位：点）
            image.setAlignment(Image.ALIGN_CENTER);  // 设置图片居中显示
            // 将图片添加到文档
            document.add(image);

            // 关闭文档
            document.close();

            // 获取 PDF 的 byte[]
            byte[] pdfBytes = baos.toByteArray();
            return pdfBytes;
        } catch (Exception e) {
            logger.error("", e);
        } finally {
            // 确保输出流被关闭
            try {
                // 确保文档关闭
                if (document.isOpen()) {
                    document.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 确保输出流被关闭
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (baos != null) {
                    baos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
